package com.yeskery.transfer.handler;

import com.yeskery.transfer.config.DataBaseProperties;
import com.yeskery.transfer.core.KeyList;
import com.yeskery.transfer.core.Resource;
import com.yeskery.transfer.core.Result;
import com.yeskery.transfer.data.ConnectionKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.shell.ResultHandler;
import org.springframework.stereotype.Component;

/**
 * 配置信息结果处理对象
 *
 * @author shuangjiang.du
 * @date 2018-12-13 09:10
 * @version 1.0
 */
@Component
public class TransferPropertiesResultHandler implements ResultHandler<DataBaseProperties.TransferProperties> {

	private final ConnectionKit connectionKit;

	private final Resource resource;

	@Autowired
	public TransferPropertiesResultHandler(ConnectionKit connectionKit, Resource resource) {
		this.connectionKit = connectionKit;
		this.resource = resource;
	}

	@Override
	public void handleResult(DataBaseProperties.TransferProperties transferProperties) {
		String content = "[Host:" + transferProperties.getHost() + "]\n"
				+ "[Port:" + transferProperties.getPort() +"]\n"
				+ "[Database:" + transferProperties.getDatabase() + "]\n"
				+ "[Username:" + transferProperties.getUsername() + "]\n"
				+ "[Password:" + transferProperties.getPassword() + "]";
		Result result = new Result();
		result.setTitle("Read Database Configuration");
		result.setContent(content);
		result.setTips("If settings incorrect, run again.");
		System.out.println(result.output());
		System.out.println();
		System.out.println(result.createContentLine("Test Connection"));
		System.out.println(result.createBlankLine());
		boolean success = connectionKit.testConnection(transferProperties);
		System.out.println(success ? result.createContentLine("Success")
				: result.createContentLine("Failure, Check database configuration."));
		System.out.println(result.createBlankLine());
		DataBaseProperties dataBaseProperties = resource.get(KeyList.DATA_CONFIG_KEY, DataBaseProperties.class);
		if (transferProperties.equals(dataBaseProperties.getServerTransferProperties())) {
			resource.add(KeyList.SERVER_CONFIG_VALID, success);
		} else {
			resource.add(KeyList.CLIENT_CONFIG_VALID, success);
		}
	}
}
